package com.hjd.shop.mq;

import com.alibaba.fastjson.JSON;
import com.hjd.shop.api.service.SOrderService;
import com.hjd.shop.constant.ShopCode;
import com.hjd.shop.constant.SystemUser;
import com.hjd.shop.entity.SOrder;
import com.hjd.shop.mapper.SOrderMapper;
import com.hjd.shop.pojo.MqEntity;
import lombok.extern.slf4j.Slf4j;
import org.apache.rocketmq.common.message.Message;
import org.apache.rocketmq.common.message.MessageExt;
import org.apache.rocketmq.spring.annotation.MessageModel;
import org.apache.rocketmq.spring.annotation.RocketMQMessageListener;
import org.apache.rocketmq.spring.core.RocketMQListener;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.util.Date;

/**
 * @Author: hjd
 * @Date: 2020/10/28 0028 22:00
 * @Des: rockmq监听类
 * 1.首先需要实现RocketMQListener接口 并重写 onMessage方法
 *   PS:RocketMQListener<T> 后面的泛型就是消息的生产者发送过来的消息的类型。
 * 2.其中rocketmq的messageModel（消息模型）需要设置为 广播(MessageModel.BROADCASTING)，
 * 因为当 确认订单 发生异常时，其他服务都需要接收到 mq的消息。
 */
@Component
@RocketMQMessageListener(topic = "${mq.order.topic}",consumerGroup = "${mq.order.consumer.group.name}",
        messageModel = MessageModel.BROADCASTING)
@Slf4j
public class OrderCancelMqListener implements RocketMQListener<MessageExt> {
    @Autowired
    private SOrderService orderService;
    @Override
    public void onMessage(MessageExt message) {
        MqEntity mqEntity = null;
        try {
            //1.解析消息内容
            String msgId = message.getMsgId();
            String body = new String(message.getBody(), "UTF-8");
            mqEntity = JSON.parseObject(body, MqEntity.class);
            log.info("消息:"+msgId+"接收成功!");
            if(mqEntity.getOrderId()!=null){
                //2.查询订单
                log.info("订单:"+mqEntity.getOrderId()+"开始取消!");
                SOrder order = orderService.selectById(mqEntity.getOrderId());
                //3.更改订单状态为取消
                order.setOrderStatus(ShopCode.SHOP_ORDER_CANCEL.getCode())
                        .setModifyUser(SystemUser.SYSTEM_USER)
                        .setModifyTime(new Date());
                orderService.confirmOrder(order);
                log.info("订单:"+mqEntity.getOrderId()+"取消成功!");
            }

        }catch (Exception e){
            e.printStackTrace();
            log.info("订单:"+mqEntity.getOrderId()+"取消失败!");
        }

    }
}
